package com.sdyc.ndmp.cls.engine;

import com.google.common.collect.ImmutableMap;
import com.huaban.analysis.jieba.JiebaCusDictSegmenter;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.WordDictionary;
import com.sdyc.ndmp.cls.dtd.Condition;
import com.sdyc.ndmp.cls.dtd.Sentence;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import scala.Tuple2;

import java.util.*;

/**
 *
 * <p>
 *     该类为 Keyword 条件过滤的引擎
 * </p>
 *
 */
public class Data720Engine {

    /**
     * LOG
     */
    private static Log LOG = LogFactory.getLog(Data720Engine.class);


    /**
     * 节点条件
     */
    private Condition condition;


    /**
     * 过滤器
     */
    protected Filter filter;

    /**
     * 词典
     */
    protected WordDictionary wordDict;


    /**
     * 无参构造
     */
    public Data720Engine() {
    }

    /**
     *
     * 过滤条件的初始化
     *
     * @param condition
     */
    public void init(Condition condition) {
        LOG.info("init " + condition);
        this.condition = condition;
        filter = FilterFactory.newInstance(condition);


        // 所有条件包含的词
        List<String> words = new LinkedList<>();

        // 规则内包含的词
        Map<String, Set<String>> rules = condition.getRule();
        for (Map.Entry<String, Set<String>> entry : rules.entrySet()) {
            words.addAll(entry.getValue());
        }

        wordDict = WordDictionary.newInstance(words);
    }


    /**
     * 给每一条帖子应用该规则
     * @param sentence post
     * @return 返回是否应用成功.
     */
    public Map<String, Object> rule(Sentence sentence) {
        JiebaCusDictSegmenter jieba = new JiebaCusDictSegmenter();
        String text = sentence.getTitle() + ",   " + sentence.getContent();

        // 将句子和词全部放在字符串中
        List<String> segs = jieba.sentenceProcess(text, wordDict, false);
        // 存放设置了词间宽的句子和词
        Map<String, Tuple2<Integer, Integer>> keywordRange = new HashMap(segs.size());
        for (String seg : segs) {
            keywordRange.put(seg, new Tuple2<Integer, Integer>(0, 0));
        }
        // 调用accept方法，判断有没有主体词
        boolean isp = filter.accept(new DataKeywords(text, keywordRange));
        // 放回是否匹配规则的信息
        return ImmutableMap.<String, Object>of("success", isp, "message", "data:" + sentence);
    }


    public static void main(String[] args) {
        JiebaCusDictSegmenter jiebaCusDictSegmenter = new JiebaCusDictSegmenter();
        List dict = Arrays.asList(new String[]{"PM2.5 10","苯", "项目", "大项目", "24口", "怀抱", "项"});
        List strings = jiebaCusDictSegmenter.sentenceProcess("PM2.5和苯超标,各大项目纷纷投身于Git的24口怀抱。", dict, false);
        System.out.println(strings);
    }

}
